package com.wxm.dom4j.base;

import com.wxm.dom4j.base.Xml;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.net.URL;

/**
 * <p>
 *      Xml文件解析
 * </p>
 *
 * @author: wxm
 * @Date: 2021/9/28
 */
public class XmlFile implements Xml {
    /**
     * 类型
     */
    private final Integer type;

    /**
     * 文件
     */
    private File xmlFile;

    /**
     * 文件url
     */
    private String fileUrl;

    /**
     * 文件流
     */
    private InputStream inputStream;

    public XmlFile(File xmlFile) {
        this.xmlFile = xmlFile;
        this.type = 1;
    }

    public XmlFile(String fileUrl) {
        this.fileUrl = fileUrl;
        this.type = 2;
    }

    public XmlFile(InputStream inputStream) {
        this.inputStream = inputStream;
        this.type = 3;
    }

    @Override
    public Document getDocument() throws Exception {
        SAXReader saxReader = new SAXReader();

        switch (type){
            case 1: return saxReader.read(this.xmlFile);
            case 2: return saxReader.read(new URL(this.fileUrl));
            case 3: return saxReader.read(inputStream);
        }
        return null;
    }
}
